package com.ouwen.smartpay.service.chain.slots.idempotent;

import com.fm.core.common.boot.Apps;
import com.google.common.collect.Lists;
import com.ouwen.smartpay.entity.OrderDetail;
import com.ouwen.smartpay.entity.OrderInfo;
import com.ouwen.smartpay.openapi.order.ServiceOrder;
import com.ouwen.smartpay.openapi.result.ServiceResult;
import com.ouwen.smartpay.service.OrderDetailService;
import com.ouwen.smartpay.service.OrderInfoService;
import com.ouwen.smartpay.service.chain.context.Context;
import com.ouwen.smartpay.service.chain.slotchain.AbstractLinkedProcessorSlot;
import com.ouwen.smartpay.utils.BeanUtil;
import org.springframework.context.ApplicationContext;

import static com.fm.core.common.enums.TranStatus.*;

/**
 * @author <a href="http://youngitman.tech">青年IT男</a>
 * @version v1.0.0
 * @className IdempotentSlot
 * @description 幂等性校验
 * @JunitTest: {@link  }
 * @date 2020-04-26 11:06
 **/
public class IdempotentFinalStateReturnSlot extends AbstractLinkedProcessorSlot<ServiceOrder> {

    private OrderDetailService orderDetailService;

    @Override
    public void entry(Context context, ServiceOrder order, Object... args) throws Throwable {

        ServiceResult serviceResult = (ServiceResult) args[0];

        ApplicationContext applicationContext = Apps.getApplicationContext();

        OrderInfoService orderInfoService = applicationContext.getBean(OrderInfoService.class);

        orderDetailService = applicationContext.getBean(OrderDetailService.class);

        //每一次请求请求流水号必须唯一
        OrderInfo orderInfo = orderInfoService.findOrderInfoByPartnerIdAndAndSubParentIdRequestNo(order.getPartnerId(), order.getSubPartnerId(), order.getRequestNo());

        OrderDetail orderDetail = null;

        if (orderInfo != null) {

            //对请求体进行持久化
            orderDetail = orderDetailService.findOrderDetailResponseInfoByOrderId(orderInfo.getId(), orderInfo.getPartnerId(), orderInfo.getSubPartnerId());

        }

        if (orderInfo != null && orderDetail != null
                && Lists.newArrayList(FTS01, FTS02, FTS03,
                FTS04, FTS05, FTS06, FTS07).contains(orderInfo.getTranStatus())) {

            if (orderDetail != null && orderDetail.getResponseInfo() != null) {

                //存在终态 直接返回
                serviceResult.setDatas(BeanUtil.jsonToMap(orderDetail.getResponseInfo()));

            }

            context.setIdempotentBreak(true);

            exit(context, order, args, orderInfo);

        } else {

            fireEntry(context, order, args);

        }
    }

    @Override
    public void exit(Context context, Object... args) {

        fireExit(context, args);

    }
}
